package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.SysHealthData;
import com.ruoyi.system.service.IHealthDataParseService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 健康数据解析服务实现类
 *
 * @author ruoyi
 */
@Service
public class HealthDataParseServiceImpl implements IHealthDataParseService {

    /**
     * 解析健康数据值
     *
     * @param featureType  特征类型
     * @param featureValue 特征值
     * @return 解析后的数据Map
     */
    @Override
    public Map<String, Object> parseHealthData(Long featureType, String featureValue) {
        Map<String, Object> result = new HashMap<>();

        if (featureValue == null || featureValue.trim().isEmpty()) {
            return result;
        }

        SysHealthData.FeatureType type = SysHealthData.FeatureType.fromValue(featureType);
        if (type == null) {
            result.put("value", featureValue);
            return result;
        }

        try {
            switch (type) {
                case OFFLINE:
                    result.put("status", "1".equals(featureValue) ? "在线" : "离线");
                    break;

                case HEART_RATE:
                case BLOOD_OXYGEN:
                case TEMPERATURE:
                case CONTINUOUS_HEART_RATE:
                case HRV:
                case URIC_ACID:
                case RESPIRATORY_RATE:
                case PRESSURE:
                case FATIGUE:
                case BATTERY:
                    result.put("value", Integer.parseInt(featureValue));
                    break;

                case BLOOD_PRESSURE:
                    String[] bpValues = featureValue.split(",");
                    if (bpValues.length >= 2) {
                        // 收缩压
                        result.put("systolic", Integer.parseInt(bpValues[0].trim()));
                        // 舒张压
                        result.put("diastolic", Integer.parseInt(bpValues[1].trim()));
                    }
                    break;

                case SLEEP:
                    String[] sleepValues = featureValue.split(",");
                    if (sleepValues.length >= 6) {
                        result.put("startTime", sleepValues[0].trim());
                        result.put("endTime", sleepValues[1].trim());
                        result.put("deepSleep", Integer.parseInt(sleepValues[2].trim()));
                        result.put("lightSleep", Integer.parseInt(sleepValues[3].trim()));
                        result.put("awake", Integer.parseInt(sleepValues[4].trim()));
                        result.put("score", Integer.parseInt(sleepValues[5].trim()));
                    }
                    break;

                case LOCATION:
                    String[] locationValues = featureValue.split(",");
                    if (locationValues.length >= 3) {
                        result.put("longitude", Double.parseDouble(locationValues[0].trim()));
                        result.put("latitude", Double.parseDouble(locationValues[1].trim()));
                        result.put("address", locationValues[2].trim());
                    }
                    break;

                case BLOOD_GLUCOSE:
                    String[] bgValues = featureValue.split(",");
                    if (bgValues.length >= 2) {
                        result.put("glucose", Double.parseDouble(bgValues[0].trim()));
                        result.put("mealTime", Integer.parseInt(bgValues[1].trim()));
                    }
                    break;

                case BLOOD_LIPIDS:
                    String[] lipidValues = featureValue.split(",");
                    if (lipidValues.length >= 4) {
                        result.put("totalCholesterol", Double.parseDouble(lipidValues[0].trim()));
                        result.put("triglycerides", Double.parseDouble(lipidValues[1].trim()));
                        result.put("ldlCholesterol", Double.parseDouble(lipidValues[2].trim()));
                        result.put("hdlCholesterol", Double.parseDouble(lipidValues[3].trim()));
                    }
                    break;

                case PPG_DATA:
                    String[] ppgValues = featureValue.split(",");
                    result.put("ppgData", ppgValues);
                    break;

                case LASER_THERAPY:
                    String[] therapyValues = featureValue.split(",");
                    if (therapyValues.length >= 4) {
                        result.put("intensity", Integer.parseInt(therapyValues[0].trim()));
                        result.put("duration", Integer.parseInt(therapyValues[1].trim()));
                        result.put("startTime", Long.parseLong(therapyValues[2].trim()));
                        result.put("endTime", Long.parseLong(therapyValues[3].trim()));
                    }
                    break;

                default:
                    result.put("value", featureValue);
                    break;
            }
        } catch (Exception e) {
            result.put("value", featureValue);
            result.put("parseError", e.getMessage());
        }

        return result;
    }

    /**
     * 验证健康数据值格式
     *
     * @param featureType  特征类型
     * @param featureValue 特征值
     * @return 是否有效
     */
    @Override
    public boolean validateHealthData(Long featureType, String featureValue) {
        if (featureValue == null || featureValue.trim().isEmpty()) {
            return false;
        }

        SysHealthData.FeatureType type = SysHealthData.FeatureType.fromValue(featureType);
        if (type == null) {
            // 未知类型默认有效
            return true;
        }

        try {
            switch (type) {
                case OFFLINE:
                    return Pattern.matches("^[01]$", featureValue);

                case HEART_RATE:
                case BLOOD_OXYGEN:
                case TEMPERATURE:
                case CONTINUOUS_HEART_RATE:
                case HRV:
                case URIC_ACID:
                case RESPIRATORY_RATE:
                case PRESSURE:
                case FATIGUE:
                case BATTERY:
                    Integer.parseInt(featureValue);
                    return true;

                case BLOOD_PRESSURE:
                    String[] bpValues = featureValue.split(",");
                    if (bpValues.length != 2) {
                        return false;
                    }
                    Integer.parseInt(bpValues[0].trim());
                    Integer.parseInt(bpValues[1].trim());
                    return true;

                case SLEEP:
                    String[] sleepValues = featureValue.split(",");
                    return sleepValues.length >= 6;

                case LOCATION:
                    String[] locationValues = featureValue.split(",");
                    if (locationValues.length < 3) {
                        return false;
                    }
                    Double.parseDouble(locationValues[0].trim());
                    Double.parseDouble(locationValues[1].trim());
                    return true;

                case BLOOD_GLUCOSE:
                    String[] bgValues = featureValue.split(",");
                    if (bgValues.length != 2) {
                        return false;
                    }
                    Double.parseDouble(bgValues[0].trim());
                    Integer.parseInt(bgValues[1].trim());
                    return true;

                case BLOOD_LIPIDS:
                    String[] lipidValues = featureValue.split(",");
                    if (lipidValues.length != 4) {
                        return false;
                    }
                    for (String value : lipidValues) {
                        Double.parseDouble(value.trim());
                    }
                    return true;

                case PPG_DATA:
                    String[] ppgValues = featureValue.split(",");
                    for (String value : ppgValues) {
                        Integer.parseInt(value.trim());
                    }
                    return true;

                case LASER_THERAPY:
                    String[] therapyValues = featureValue.split(",");
                    if (therapyValues.length != 4) {
                        return false;
                    }
                    Integer.parseInt(therapyValues[0].trim());
                    Integer.parseInt(therapyValues[1].trim());
                    Long.parseLong(therapyValues[2].trim());
                    Long.parseLong(therapyValues[3].trim());
                    return true;

                default:
                    return true;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 格式化健康数据值用于显示
     *
     * @param featureType  特征类型
     * @param featureValue 特征值
     * @return 格式化后的显示文本
     */
    @Override
    public String formatHealthDataForDisplay(Long featureType, String featureValue) {
        if (featureValue == null || featureValue.trim().isEmpty()) {
            return "--";
        }

        SysHealthData.FeatureType type = SysHealthData.FeatureType.fromValue(featureType);
        if (type == null) {
            return featureValue;
        }

        try {
            switch (type) {
                case OFFLINE:
                    return "1".equals(featureValue) ? "在线" : "离线";

                case HEART_RATE:

                case RESPIRATORY_RATE:

                case CONTINUOUS_HEART_RATE:
                    return featureValue + " 次/分钟";

                case BLOOD_PRESSURE:
                    String[] bpValues = featureValue.split(",");
                    if (bpValues.length >= 2) {
                        return bpValues[0].trim() + "/" + bpValues[1].trim() + " mmHg";
                    }
                    break;

                case BLOOD_OXYGEN:

                case BATTERY:
                    return featureValue + "%";

                case TEMPERATURE:
                    return featureValue + "°C";

                case LOCATION:
                    String[] locationValues = featureValue.split(",");
                    if (locationValues.length >= 3) {
                        return locationValues[2].trim();
                    }
                    break;

                case URIC_ACID:
                    return featureValue + " μmol/L";

                case BLOOD_GLUCOSE:
                    String[] bgValues = featureValue.split(",");
                    if (bgValues.length >= 2) {
                        String mealTime = Integer.parseInt(bgValues[1].trim()) < 0 ? "餐前" : "餐后";
                        return bgValues[0].trim() + " mmol/L (" + mealTime + ")";
                    }
                    break;

                case PRESSURE:
                    return featureValue + " (0-100)";

                case BLOOD_LIPIDS:
                    String[] lipidValues = featureValue.split(",");
                    if (lipidValues.length >= 4) {
                        return String.format("TC:%s TC:%s LDL:%s HDL:%s mmol/L",
                                lipidValues[0].trim(), lipidValues[1].trim(),
                                lipidValues[2].trim(), lipidValues[3].trim());
                    }
                    break;

                case PPG_DATA:
                    return "PPG数据 (" + featureValue.split(",").length + "个数据点)";

                case LASER_THERAPY:
                    String[] therapyValues = featureValue.split(",");
                    if (therapyValues.length >= 4) {
                        return String.format("强度:%s 时长:%s秒",
                                therapyValues[0].trim(), therapyValues[1].trim());
                    }
                    break;

                case SLEEP:
                    String[] sleepValues = featureValue.split(",");
                    if (sleepValues.length >= 6) {
                        return String.format("得分:%s 深睡:%s 浅睡:%s 清醒:%s",
                                sleepValues[5].trim(), sleepValues[2].trim(),
                                sleepValues[3].trim(), sleepValues[4].trim());
                    }
                    break;
                case HRV:
                case FATIGUE:

                default:
                    return featureValue;
            }
        } catch (Exception e) {
            return featureValue;
        }

        return featureValue;
    }

    /**
     * 获取健康数据的单位
     *
     * @param featureType 特征类型
     * @return 单位字符串
     */
    @Override
    public String getHealthDataUnit(Long featureType) {
        SysHealthData.FeatureType type = SysHealthData.FeatureType.fromValue(featureType);
        if (type == null) {
            return "";
        }

        switch (type) {
            case HEART_RATE:
            case CONTINUOUS_HEART_RATE:
            case RESPIRATORY_RATE:
                return "次/分钟";
            case BLOOD_PRESSURE:
                return "mmHg";
            case BLOOD_OXYGEN:
            case BATTERY:
                return "%";
            case TEMPERATURE:
                return "°C";
            case URIC_ACID:
                return "μmol/L";
            case BLOOD_GLUCOSE:
            case BLOOD_LIPIDS:
                return "mmol/L";
            default:
                return "";
        }
    }

    /**
     * 获取健康数据的正常范围
     *
     * @param featureType 特征类型
     * @return 正常范围描述
     */
    @Override
    public String getHealthDataNormalRange(Long featureType) {
        SysHealthData.FeatureType type = SysHealthData.FeatureType.fromValue(featureType);
        if (type == null) {
            return "";
        }

        switch (type) {
            case HEART_RATE:
            case CONTINUOUS_HEART_RATE:
                return "60-100 次/分钟";
            case BLOOD_PRESSURE:
                return "收缩压90-140mmHg，舒张压60-90mmHg";
            case BLOOD_OXYGEN:
                return "95-100%";
            case TEMPERATURE:
                return "36.1-37.2°C";
            case URIC_ACID:
                return "男性208-428μmol/L，女性155-357μmol/L";
            case BLOOD_GLUCOSE:
                return "3.9-6.1 mmol/L (空腹)";
            case RESPIRATORY_RATE:
                return "12-20 次/分钟";
            case PRESSURE:
                return "0-30 (正常)";
            default:
                return "";
        }
    }

    /**
     * 判断健康数据是否在正常范围内
     *
     * @param featureType  特征类型
     * @param featureValue 特征值
     * @return 是否正常
     */
    @Override
    public boolean isHealthDataNormal(Long featureType, String featureValue) {
        if (featureValue == null || featureValue.trim().isEmpty()) {
            return false;
        }

        SysHealthData.FeatureType type = SysHealthData.FeatureType.fromValue(featureType);
        if (type == null) {
            // 未知类型默认正常
            return true;
        }

        try {
            switch (type) {
                case HEART_RATE:
                case CONTINUOUS_HEART_RATE:
                    int heartRate = Integer.parseInt(featureValue);
                    return heartRate >= 60 && heartRate <= 100;

                case BLOOD_PRESSURE:
                    String[] bpValues = featureValue.split(",");
                    if (bpValues.length >= 2) {
                        int systolic = Integer.parseInt(bpValues[0].trim());
                        int diastolic = Integer.parseInt(bpValues[1].trim());
                        return systolic >= 90 && systolic <= 140 && diastolic >= 60 && diastolic <= 90;
                    }
                    break;

                case BLOOD_OXYGEN:
                    int bloodOxygen = Integer.parseInt(featureValue);
                    return bloodOxygen >= 95 && bloodOxygen <= 100;

                case TEMPERATURE:
                    double temperature = Double.parseDouble(featureValue);
                    return temperature >= 36.1 && temperature <= 37.2;

                case BLOOD_GLUCOSE:
                    String[] bgValues = featureValue.split(",");
                    if (bgValues.length >= 2) {
                        double glucose = Double.parseDouble(bgValues[0].trim());
                        return glucose >= 3.9 && glucose <= 6.1;
                    }
                    break;

                case RESPIRATORY_RATE:
                    int respiratoryRate = Integer.parseInt(featureValue);
                    return respiratoryRate >= 12 && respiratoryRate <= 20;

                case PRESSURE:
                    int pressure = Integer.parseInt(featureValue);
                    return pressure >= 0 && pressure <= 30;

                // 其他类型默认正常
                default:
                    return true;
            }
        } catch (Exception e) {
            return false;
        }

        return true;
    }
}